<?php

namespace App\Http\Controllers\Api;

use AlipayNotify;
use AlipaySubmit;
use App\Enum\CardRecordCode;
use App\Enum\PayRecordCode;
use App\Models\CardModel;
use App\Models\PayRecordModel;
use App\Utils\Build;
use App\Utils\Message;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;


class PayController extends BaseController
{
    public function confirm(
        Request $request,
        PayRecordModel $payRecordModel
    ) {
        $type = $request->pay_type;
        $phone = $request->phone;
        $money = $request->money;
        if (empty($type)) {
            return Message::show_message(false, '支付方式不能为空');
        }

        if (empty($phone)) {
            return Message::show_message(false, '手机号码不能为空');
        }

        if (!floatval($money) > 0) {
            return Message::show_message(false, '无效订单');
        }

        $config['partner'] = env('ALIPAY_ID', '');
        $config['key'] = env('ALIPAY_KEY', '');
        $config['sign_type'] = env('ALIPAY_SIGN_TYPE', '');
        $config['input_charset'] = env('ALIPAY_CHARSET', '');
        $config['alipay_transport'] = env('ALIPAY_TRANSPORT', '');
        $config['apiurl'] = env('ALIPAY_APIURL', '');


        switch ($type) {
            case 'alipay':
                DB::beginTransaction();
                try {
                    // 支付参数
                    $parameter = [
                        'pid' => env('ALIPAY_ID', ''),
                        'type' => $request->type,
                        'notify_url' => env('ALIPAY_NOTIFY_URL', ''),
                        'return_url' => env('ALIPAY_RETURN_URL', ''),
                        'out_trade_no' => Build::order_number(),
                        'name' => '话费充值',
                        'money' => floatval($money),
                        // 'sitename' => '字符圈话费充值'
                    ];

                    $alipaySubmit = new AlipaySubmit($config);
                    $htmlText = $alipaySubmit->buildRequestForm($parameter);

                    // 写入支付记录表
                    $payRecordModel::create([
                        'out_trade_no' => $parameter['out_trade_no'],
                        'phone' => $phone,
                        'money' => $money,
                        'name' => $parameter['name']
                    ]);
                    DB::commit();
                    return Message::show_message(true, 'success', $htmlText);
                } catch (Exception $error) {
                    DB::rollBack();
                    return Message::show_message(false, $error->getMessage());
                }
                break;
            case 'weixin':

                break;
            default:
                return Message::show_message(false, '暂不支持的支付方式');
        }
    }

    public function alipay_notify(
        Request $request,
        PayRecordModel $payRecordModel,
        CardModel $cardModel
    ) {
        $config['partner'] = env('ALIPAY_ID', '');
        $config['key'] = env('ALIPAY_KEY', '');
        $config['sign_type'] = env('ALIPAY_SIGN_TYPE', '');
        $config['input_charset'] = env('ALIPAY_CHARSET', '');
        $config['ALIPAY_TRANSPORT'] = env('ALIPAY_TRANSPORT', '');
        $config['apiurl'] = env('ALIPAY_APIURL', '');

        $alipayNotify = new AlipayNotify($config);

        $verifyResult = $alipayNotify->verifyNotify();

        if ($verifyResult) { // 验证成功
            // 商户订单号
            $payOrder['out_trade_no'] = $request->get('out_trade_no');
            // 彩虹易支付交易号
            $payOrder['trade_no'] = $request->get('trade_no');
            // 交易状态
            $payOrder['trade_status'] = $request->get('trade_status');
            // 支付方式
            $payOrder['type'] = $request->get('type');
            // 商品名称
            $payOrder['name'] = $request->get('name');
            // 商品金额
            $payOrder['money'] = $request->get('money');

            // 支付成功
            if ($payOrder['trade_status'] == 'TRADE_SUCCESS') {
                DB::beginTransaction();
                try {

                    Log::debug($payOrder);
                    // 更新支付记录表
                    $payRecordModel->where(['out_trade_no' => $payOrder['out_trade_no']])->update([
                        'status' => PayRecordCode::PAY_SUCCESS,
                        'pay_money' => $payOrder['money'],
                        'trade_no' => $payOrder['trade_no'],
                        'trade_status' => $payOrder['trade_status'],
                        'type' => $payOrder['type']
                    ]);

                    // 获取最新的充值记录
                    $payRecord = $payRecordModel->where(['out_trade_no' => $payOrder['out_trade_no']])->first();

                    // 获取充值卡信息
                    $cardInfo = $cardModel->where(['phone' => $payRecord->phone])->first();

                    if (empty($cardInfo)) { // 第一次开卡
                        // 激活卡
                        $cardModel->create([
                            'status' => CardRecordCode::IS_USE_CODE,
                            'phone' => $payRecord->phone,
                            'product_id' => env('TOPUP_PRODUCT_ID', ''),
                            'card_uuid' => Str::uuid(),
                            'remaining_num' => env('TOPUP_NUMBER'),
                            'total_num' => env('TOPUP_NUMBER'),
                            'get_time' => now(),
                            'due_time' => now()->addYears((int) env('CARD_VALIDITY', 1)),
                        ]);
                    }else{ // 已经开卡，更新次数
                        $cardModel->where(['phone'=>$cardInfo->phone])->update([
                            'remaining_num' => (int)$cardInfo->remaining_num + (int)env('TOPUP_NUMBER'),
                            'total_num' => (int)$cardInfo->total_num + (int)env('TOPUP_NUMBER')
                        ]);
                    }



                    DB::commit();

                    echo 'success';
                } catch (Exception $error) {
                    DB::rollBack();
                    echo 'fail';
                }
            }
        } else { // 验证失败
            Log::error('alipay fail');
            echo 'fail';
        }
    }

    /**
     * 返回跳转地址
     *
     * @param Request $request
     * @param PayRecordModel $payRecordModel
     * @return void
     */
    public function alipay_return(
        Request $request,
        PayRecordModel $payRecordModel
    ) {
        $outTradeNo = $request->get('out_trade_no');
        if (empty($outTradeNo)) {
            return Message::show_message(false, '无效的订单号');
        }
        $payInfo = $payRecordModel->where(['out_trade_no' => $outTradeNo])->first();
        if ($payInfo->status == PayRecordCode::PAY_SUCCESS) {
            return Message::show_message(true, '支付成功');
        }
        return Message::show_message(false, '支付失败');
    }
}
